package com.gzx.plugin.tjzy.modular.allocate.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.gzx.plugin.tjzy.modular.allocate.entity.GzxAllocateRecord;
import com.gzx.plugin.tjzy.modular.allocate.entity.vo.GzxAllocateCaseExcelVo;
import com.gzx.plugin.tjzy.modular.allocate.entity.vo.GzxAllocateRecordVo;
import com.gzx.plugin.tjzy.modular.allocate.mapper.GzxAllocateRecordMapper;
import com.gzx.plugin.tjzy.modular.allocate.service.GzxAllocateRecordDbService;
import com.gzx.plugin.tjzy.modular.gzxcase.entity.GzxWckjOverdue;
import com.gzx.plugin.tjzy.modular.gzxcase.mapper.GzxWckjOverdueMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.consts.IntConstant;
import vip.xiaonuo.common.util.CommonCryptogramUtil;
import vip.xiaonuo.common.util.CommonDateUtil;
import vip.xiaonuo.common.util.CommonSleepUtil;
import vip.xiaonuo.common.util.CommonWechatUtil;
import vip.xiaonuo.common.wechat.enums.WechatNotificationType;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static org.apache.commons.lang.StringEscapeUtils.escapeSql;

/**
 * @author zjt
 * @description
 * @date 2025/5/21 16:33
 */
@Service
@RequiredArgsConstructor
public class GzxAllocateRecordDbServiceImpl implements GzxAllocateRecordDbService {

    private final GzxAllocateRecordMapper allocateRecordMapper;

    private final GzxWckjOverdueMapper wckjOverdueMapper;

    /**
     * 分页查询分案记录
     *
     * @param page               分页参数
     * @param lambdaQueryWrapper 查询条件
     * @return
     */
    @Override
    @DS("tjzy")
    public Page<GzxAllocateRecordVo> pageList(Page page, LambdaQueryWrapper<GzxAllocateRecord> lambdaQueryWrapper) {
        return allocateRecordMapper.selectVoPage(new Page<>(page.getCurrent(), page.getSize()), lambdaQueryWrapper);
    }

    /**
     * 查询分案记录
     *
     * @param lambdaQueryWrapper
     * @return
     */
    @Override
    @DS("tjzy")
    public List<GzxAllocateRecord> listAll(LambdaQueryWrapper<GzxAllocateRecord> lambdaQueryWrapper) {
        return allocateRecordMapper.selectList(lambdaQueryWrapper);
    }

    /**
     * 根据批次号和债务人卡ID列表查询每组最新记录（按ID降序）
     *
     * @param batchNumber
     * @param debtorCardIdList
     * @return
     */
    @Override
    @DS("tjzy")
    public List<GzxAllocateRecord> selectLatestRecordsByBatchAndDebtorCards(String batchNumber, List<String> debtorCardIdList) {
        return allocateRecordMapper.selectLatestRecordsByBatchAndDebtorCards(batchNumber, debtorCardIdList);
    }

    /**
     * 批量保存分案记录
     *
     * @param allocateRecordList
     */
    @Override
    @DS("tjzy")
    public void saveBatch(List<GzxAllocateRecord> allocateRecordList) {
        String currentTime = CommonDateUtil.getCurrentTimeStr();
        List<List<GzxAllocateRecord>> allocateBatchList = Lists.partition(allocateRecordList, IntConstant.VALUE_1000);
        for (List<GzxAllocateRecord> allocateBatch : allocateBatchList) {
            String sql = allocateBatch.stream()
                    .map(s -> String.format("('%s','%s', '%s', '%s', '%s', '%s','%s')",
                            escapeSql(String.valueOf(s.getType())),
                            escapeSql(s.getBatchNumber()),
                            escapeSql(CommonCryptogramUtil.doSm1AesEncrypt(s.getDebtorCardId())),
                            escapeSql(String.valueOf(s.getMediatorId())),
                            escapeSql(s.getTenantId()),
                            escapeSql(s.getCreateUser()),
                            escapeSql(currentTime)))
                    .collect(Collectors.joining(", ")).replace("'null'", "null");
            allocateRecordMapper.insertBatchByValSql(sql);
            CommonSleepUtil.sleep(IntConstant.VALUE_100);
        }
    }

    @Override
    @DS("tjzy")
    public void modifyCaseOverdueAmount(List<GzxAllocateCaseExcelVo> allocateCaseExcelVoList) {
        List<GzxWckjOverdue> wckjOverdueList = allocateCaseExcelVoList.stream()
                .filter(s -> s.getOverdueAmount() != null) // 过滤掉 overdueAmount 为 null 的元素
                .map(s -> new GzxWckjOverdue(s.getBatchNumber(), CommonCryptogramUtil.doSm1AesEncrypt(s.getDebtorCardId()), s.getOverdueAmount())).toList();
        if (CollectionUtil.isNotEmpty(wckjOverdueList)) {
            long allocateStartTime = System.currentTimeMillis();
            SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
            CommonWechatUtil.sendMessage("案件分配", WechatNotificationType.TASK_NOTICE, List.of(loginUser.getEmpNo()), loginUser.getName() + "的分案任务", "开始补全逾期金额");
            List<List<GzxWckjOverdue>> bb = Lists.partition(wckjOverdueList, IntConstant.VALUE_1000);
            bb.forEach(batch -> {
                wckjOverdueMapper.insertOverdue(batch);
                CommonSleepUtil.sleep(IntConstant.VALUE_100);
            });
            Set<String> batchNumberSet = wckjOverdueList.stream().map(GzxWckjOverdue::getBatchNumber).collect(Collectors.toSet());
            for (String batchNumber : batchNumberSet) {
                wckjOverdueMapper.modifyCaseOverdueAmount(batchNumber);
            }
            CommonWechatUtil.sendMessage("案件分配", WechatNotificationType.TASK_NOTICE, List.of(loginUser.getEmpNo()), loginUser.getName() + "的分案任务", "逾期金额补全完成，耗时" + (System.currentTimeMillis() - allocateStartTime));
        }
    }
}
